Crate jsonschema

source ·
Expand description

§jsonschema

A crate for performing fast JSON Schema validation. It is fast due to schema compilation into a validation tree, which reduces runtime costs for working with schema parameters.

Supports:

  • JSON Schema drafts 4, 6, 7 (except some optional test cases);
  • Loading remote documents via HTTP(S);

Partially supported drafts (some keywords are not implemented):

  • Draft 2019-09 (requires the draft201909 feature enabled)
  • Draft 2020-12 (requires the draft202012 feature enabled)

This library is functional and ready for use, but its API is still evolving to the 1.0 API.

§Usage Examples:

A schema can be compiled with two main flavours:

  • using default configurations
let compiled_schema = JSONSchema::compile(&schema).expect("A valid schema");
  • using custom configurations (such as define a Draft version)
let compiled_schema = JSONSchema::options()
    .with_draft(Draft::Draft7)
    .compile(&schema)
    .expect("A valid schema");

§Example (CLI tool to highlight print errors)

use jsonschema::{Draft, JSONSchema};
use serde_json::json;

let schema = json!({"maxLength": 5});
let instance = json!("foo");
let compiled = JSONSchema::options()
    .with_draft(Draft::Draft7)
    .compile(&schema)
    .expect("A valid schema");
let result = compiled.validate(&instance);
if let Err(errors) = result {
    for error in errors {
        println!("Validation error: {}", error);
        println!("Instance path: {}", error.instance_path);
    }
}

Each error has an instance_path attribute that indicates the path to the erroneous part within the validated instance. It could be transformed to JSON Pointer via .to_string() or to Vec<String> via .into_vec().

Re-exports§

Modules§

Structs§

  • Full configuration to guide the JSONSchema compilation.
  • The structure that holds a JSON Schema compiled into a validation tree

Enums§

  • JSON Schema Draft version

Traits§

  • Trait that allows implementing custom validation for keywords.
  • A resolver that resolves external schema references. Internal references such as #/definitions and JSON pointers are handled internally.

Functions§

  • A shortcut for validating instance against schema. Draft version is detected automatically.

Type Aliases§